<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>区块链拍卖平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4a6bff;
            --secondary-color: #6c757d;
            --dark-color: #343a40;
            --light-color: #f8f9fa;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --bg-color: #1a1a2e;
            --card-bg-color: #16213e;
            --text-color: #e6e6e6;
            --text-secondary: #b8b8b8;
            --title-color: #ffffff;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        /* 导航栏样式 */
        nav {
            background-color: var(--card-bg-color);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
            padding: 15px 0;
            position: sticky;
            top: 0;
            z-index: 100;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .nav-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            font-size: 24px;
            font-weight: 700;
            color: var(--primary-color);
            display: flex;
            align-items: center;
        }
        
        .logo i {
            margin-right: 10px;
        }
        
        .nav-links {
            display: flex;
            list-style: none;
        }
        
        .nav-links li {
            margin-left: 30px;
        }
        
        .nav-links a {
            text-decoration: none;
            color: var(--text-secondary);
            font-weight: 500;
            transition: color 0.3s;
            position: relative;
        }
        
        .nav-links a:hover {
            color: var(--primary-color);
        }
        
        .nav-links a::after {
            content: '';
            position: absolute;
            width: 0;
            height: 2px;
            bottom: -5px;
            left: 0;
            background-color: var(--primary-color);
            transition: width 0.3s;
        }
        
        .nav-links a:hover::after {
            width: 100%;
        }
        
        .wallet-info {
            display: flex;
            align-items: center;
        }
        
        .wallet-address {
            margin-right: 15px;
            font-weight: 500;
            color: var(--text-secondary);
        }
        
        .connect-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.3s;
        }
        
        .connect-btn:hover {
            background-color: #3a5bef;
        }
        
        /* 主要内容区域 */
        .hero {
            background: linear-gradient(135deg, var(--primary-color), #6a11cb);
            color: white;
            padding: 80px 0;
            text-align: center;
            margin-bottom: 40px;
        }
        
        .hero h1 {
            font-size: 48px;
            margin-bottom: 20px;
            color: var(--title-color);
        }
        
        .hero p {
            font-size: 20px;
            max-width: 700px;
            margin: 0 auto 30px;
            color: var(--text-secondary);
        }
        
        .auction-container {
            display: flex;
            gap: 30px;
            margin-bottom: 50px;
        }
        
        /* 拍卖信息卡片 */
        .auction-info {
            flex: 1;
            background-color: var(--card-bg-color);
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .auction-info h2 {
            color: var(--primary-color);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .info-item {
            margin-bottom: 20px;
        }
        
        .info-item h3 {
            color: var(--text-secondary);
            font-size: 16px;
            margin-bottom: 8px;
        }
        
        .info-item p {
            font-size: 24px;
            font-weight: 600;
            color: var(--title-color);
        }
        
        .countdown {
            font-size: 28px;
            color: var(--danger-color);
            font-weight: 700;
        }
        
        /* 操作面板 */
        .auction-actions {
            flex: 1;
            background-color: var(--card-bg-color);
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .auction-actions h2 {
            color: var(--primary-color);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-secondary);
        }
        
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
            background-color: var(--light-color);
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            outline: none;
        }
        
        .btn {
            display: inline-block;
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            width: 100%;
            font-size: 16px;
        }
        
        .btn:hover {
            background-color: #3a5bef;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        .btn-success {
            background-color: var(--success-color);
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .btn-danger {
            background-color: var(--danger-color);
        }
        
        .btn-danger:hover {
            background-color: #c82333;
        }
        
        .btn-disabled {
            background-color: #000000;
            cursor: not-allowed;
            opacity: 0.7;
        }
        
        .btn-disabled:hover {
            transform: none;
        }
        
        /* 竞标历史 */
        .bid-history {
            background-color: var(--card-bg-color);
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            margin-bottom: 40px;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .bid-history h2 {
            color: var(--primary-color);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .history-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .history-table th, .history-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .history-table th {
            background-color: rgba(0, 0, 0, 0.2);
            font-weight: 500;
            color: var(--text-secondary);
        }
        
        .history-table tr:hover {
            background-color: rgba(255, 255, 255, 0.05);
        }
        
        /* 响应式设计 */
        @media (max-width: 992px) {
            .auction-container {
                flex-direction: column;
            }
        }
        
        /* 通知样式 */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 5px;
            z-index: 1000;
            display: flex;
            align-items: center;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
            animation: slideIn 0.3s ease-out;
            max-width: 300px;
        }
        
        .notification-success {
            background-color: var(--success-color);
            color: white;
        }
        
        .notification-error {
            background-color: var(--danger-color);
            color: white;
        }
        
        .notification-warning {
            background-color: var(--warning-color);
            color: #333;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        .close-btn {
            margin-left: 15px;
            cursor: pointer;
            font-weight: bold;
            color: white;
        }
        
        .eth-balance {
            display: flex;
            align-items: center;
            margin-top: 15px;
        }
        
        .eth-balance i {
            margin-right: 5px;
            color: var(--warning-color);
        }
        
        .balance-value {
            font-weight: 600;
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav>
        <div class="container nav-container">
            <div class="logo">
                <i class="fas fa-gavel"></i>
                <span>区块链拍卖</span>
            </div>
            <ul class="nav-links">
                <li><a href="#">首页</a></li>
                <li><a href="#">当前拍卖</a></li>
                <li><a href="#">历史拍卖</a></li>
                <li><a href="#">帮助中心</a></li>
            </ul>
            <div class="wallet-info">
                <span class="wallet-address" id="walletAddress">未连接钱包</span>
                <button class="connect-btn" id="connectBtn">连接钱包</button>
            </div>
        </div>
    </nav>

    <!-- 英雄区域 -->
    <section class="hero">
        <div class="container">
            <h1>稀有数字艺术品拍卖</h1>
            <p>参与我们的区块链拍卖，获取独一无二的数字收藏品。公平、透明、安全的拍卖体验。</p>
            <div class="countdown" id="countdown">00:00:00</div>
        </div>
    </section>

    <!-- 主要内容 -->
    <div class="container">
        <div class="auction-container">
            <!-- 拍卖信息 -->
            <div class="auction-info">
                <h2>拍卖信息</h2>
                <div class="info-item">
                    <h3>当前最高出价</h3>
                    <p id="currentHighestBid">0 ETH</p>
                </div>
                <div class="info-item">
                    <h3>最高出价者</h3>
                    <p id="currentHighestBidder">暂无</p>
                </div>
                <div class="info-item">
                    <h3>拍卖结束时间</h3>
                    <p id="auctionEndTime">--</p>
                </div>
                <div class="info-item">
                    <h3>拍卖状态</h3>
                    <p id="auctionStatus">进行中</p>
                </div>
                <div class="eth-balance">
                    <i class="fas fa-ethereum"></i>
                    <span>账户余额:</span>
                    <span class="balance-value" id="ethBalance">0 ETH</span>
                </div>
            </div>

            <!-- 操作面板 -->
            <div class="auction-actions">
                <h2>操作面板</h2>
                <div class="form-group">
                    <label for="bidAmount">出价金额 (ETH)</label>
                    <input type="number" id="bidAmount" class="form-control" placeholder="输入您的出价" min="0" step="0.01">
                </div>
                <button class="btn btn-success" id="placeBidBtn">出价</button>
                <button class="btn btn-secondary" id="withdrawBtn" style="margin-top: 15px; display: none;">提款</button>
                <button class="btn btn-danger" id="endAuctionBtn" style="margin-top: 15px; display: none;">结束拍卖</button>
            </div>
        </div>

        <!-- 竞标历史 -->
        <div class="bid-history">
            <h2>竞标历史</h2>
            <table class="history-table">
                <thead>
                    <tr>
                        <th>出价者</th>
                        <th>金额 (ETH)</th>
                        <th>时间</th>
                    </tr>
                </thead>
                <tbody id="bidHistory">
                    <tr>
                        <td colspan="3" style="text-align: center;">暂无竞标记录</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 通知 -->
    <div id="notification" class="notification notification-success" style="display: none;">
        <span id="notificationText">操作成功！</span>
        <span class="close-btn" id="closeNotification">×</span>
    </div>

    <!-- 引入以太坊和合约ABI -->
    <script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js"></script>
    <script>
        // 合约ABI - 请替换为您实际的合约ABI
        const auctionABI =[
	{
		"inputs": [],
		"name": "auctionEnd",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "bid",
		"outputs": [],
		"stateMutability": "payable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "_owner",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "_auctionLength",
				"type": "uint256"
			}
		],
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "highestBid",
				"type": "uint256"
			}
		],
		"name": "BidNotHighEnough",
		"type": "error"
	},
	{
		"inputs": [],
		"name": "withdraw",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "bidEndTime",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "highestBid",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "highestBidder",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "owner",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"name": "pendingReturns",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	}
];

        // 合约地址 - 替换为您本地部署的合约地址
        const auctionContractAddress = "0x7ef8E99980Da5bcEDcF7C10f41E55f759F6A174B";

        // 全局变量
        let web3;
        let auctionContract;
        let isWalletConnected = false;
        let currentAccount = null;
        let ethBalance = 0;

        // DOM元素
        const walletAddressEl = document.getElementById('walletAddress');
        const connectBtn = document.getElementById('connectBtn');
        const currentHighestBidEl = document.getElementById('currentHighestBid');
        const currentHighestBidderEl = document.getElementById('currentHighestBidder');
        const auctionEndTimeEl = document.getElementById('auctionEndTime');
        const auctionStatusEl = document.getElementById('auctionStatus');
        const countdownEl = document.getElementById('countdown');
        const bidAmountEl = document.getElementById('bidAmount');
        const placeBidBtn = document.getElementById('placeBidBtn');
        const withdrawBtn = document.getElementById('withdrawBtn');
        const endAuctionBtn = document.getElementById('endAuctionBtn');
        const bidHistoryEl = document.getElementById('bidHistory');
        const notificationEl = document.getElementById('notification');
        const notificationTextEl = document.getElementById('notificationText');
        const closeNotificationEl = document.getElementById('closeNotification');
        const ethBalanceEl = document.getElementById('ethBalance');

        // 初始化
        document.addEventListener('DOMContentLoaded', async function() {
            // 检查是否安装了MetaMask
            if (typeof window.ethereum !== 'undefined') {
                console.log('MetaMask is installed!');
                connectBtn.style.display = 'block';
                
                // 初始化Web3
                initializeWeb3();
                
                // 初始化合约
                initializeContract();
                
                // 尝试自动连接MetaMask
                try {
                    const accounts = await window.ethereum.request({ method: 'eth_accounts' });
                    if (accounts.length > 0) {
                        await connectWallet(accounts[0]);
                    }
                } catch (error) {
                    console.log('请手动连接钱包', error);
                }
            } else {
                showNotification('请安装MetaMask或其他以太坊钱包', 'error');
                connectBtn.style.display = 'none';
                return;
            }

            // 事件监听器
            connectBtn.addEventListener('click', () => {
                window.ethereum.request({ method: 'eth_requestAccounts' })
                    .then(accounts => connectWallet(accounts[0]))
                    .catch(error => showNotification('连接钱包失败: ' + error.message, 'error'));
            });
            
            placeBidBtn.addEventListener('click', placeBid);
            withdrawBtn.addEventListener('click', withdrawFunds);
            endAuctionBtn.addEventListener('click', endAuction);
            closeNotificationEl.addEventListener('click', () => {
                notificationEl.style.display = 'none';
            });

            // 定期更新UI
            setInterval(updateUI, 3000);
        });

        // 初始化Web3
        function initializeWeb3() {
            if (typeof window.ethereum !== 'undefined') {
                // 使用MetaMask的provider
                web3 = new Web3(window.ethereum);
                
                // 尝试切换到本地开发网络
                window.ethereum.request({
                    method: 'wallet_switchEthereumChain',
                    params: [{ chainId: '0x7a69' }] // 本地开发网络通常是0x539 (1337)
                }).catch(error => {
                    console.log('切换网络失败:', error);
                    // 如果网络不存在，可以尝试添加
                    if (error.code === 4902) {
                        window.ethereum.request({
                            method: 'wallet_addEthereumChain',
                            params: [{
                                chainId: '0x7a69',
                                chainName: 'Localhost 8545',
                                nativeCurrency: {
                                    name: 'Ether',
                                    symbol: 'ETH',
                                    decimals: 18
                                },
                                rpcUrls: ['http://127.0.0.1:8545'],
                                blockExplorerUrls: ['http://127.0.0.1:8545']
                            }]
                        });
                    }
                });
            } else {
                showNotification('请安装MetaMask或其他以太坊钱包', 'error');
                throw new Error('No Ethereum provider found');
            }
        }

        // 初始化合约
        function initializeContract() {
            auctionContract = new web3.eth.Contract(auctionABI, auctionContractAddress);
        }

        // 连接钱包
        async function connectWallet(account) {
            currentAccount = account;
            isWalletConnected = true;
            
            // 更新UI
            walletAddressEl.textContent = shortenAddress(currentAccount);
            connectBtn.textContent = '已连接';
            connectBtn.style.backgroundColor = '#28a745';
            
            // 获取余额
            await updateBalance();
            
            // 检查是否有待退还的金额
            const pending = await auctionContract.methods.pendingReturns(currentAccount).call();
            if (pending > 0) {
                withdrawBtn.style.display = 'block';
            }
            
            showNotification('钱包连接成功！', 'success');
            updateUI();
        }

        // 出价
        async function placeBid() {
            if (!isWalletConnected) {
                showNotification('请先连接钱包！', 'error');
                return;
            }
            
            const bidAmount = parseFloat(bidAmountEl.value);
            if (isNaN(bidAmount) || bidAmount <= 0) {
                showNotification('请输入有效的出价金额！', 'error');
                return;
            }
            
            try {
                // 获取当前最高价
                const currentBid = await auctionContract.methods.highestBid().call();
                
                if (bidAmount <= parseFloat(web3.utils.fromWei(currentBid, 'ether'))) {
                    showNotification(`出价必须高于当前最高价 ${web3.utils.fromWei(currentBid, 'ether')} ETH！`, 'error');
                    return;
                }
                
                // 显示加载状态
                placeBidBtn.disabled = true;
                placeBidBtn.textContent = '处理中...';
                
                // 发送交易
                await auctionContract.methods.bid().send({
                    from: currentAccount,
                    value: web3.utils.toWei(bidAmount.toString(), 'ether')
                });
                
                // 重置表单
                bidAmountEl.value = '';
                
                showNotification(`成功出价 ${bidAmount} ETH！`, 'success');
                updateUI();
            } catch (error) {
                console.error('出价失败:', error);
                showNotification('出价失败: ' + error.message, 'error');
            } finally {
                placeBidBtn.disabled = false;
                placeBidBtn.textContent = '出价';
            }
        }

        // 提款
        async function withdrawFunds() {
            if (!isWalletConnected) {
                showNotification('请先连接钱包！', 'error');
                return;
            }
            
            try {
                // 显示加载状态
                withdrawBtn.disabled = true;
                withdrawBtn.textContent = '处理中...';
                
                // 发送交易
                await auctionContract.methods.withdraw().send({
                    from: currentAccount
                });
                
                withdrawBtn.style.display = 'none';
                
                showNotification('提款成功！', 'success');
                updateUI();
                await updateBalance();
            } catch (error) {
                console.error('提款失败:', error);
                showNotification('提款失败: ' + error.message, 'error');
            } finally {
                withdrawBtn.disabled = false;
                withdrawBtn.textContent = '提款';
            }
        }

        // 结束拍卖
        async function endAuction() {
            if (!isWalletConnected) {
                showNotification('请先连接钱包！', 'error');
                return;
            }
            
            try {
                // 检查是否是所有者
                const owner = await auctionContract.methods.owner().call();
                if (currentAccount.toLowerCase() !== owner.toLowerCase()) {
                    showNotification('只有所有者可以结束拍卖！', 'error');
                    return;
                }
                
                // 显示加载状态
                endAuctionBtn.disabled = true;
                endAuctionBtn.textContent = '处理中...';
                
                // 发送交易
                await auctionContract.methods.auctionEnd().send({
                    from: currentAccount
                });
                
                showNotification('拍卖已成功结束！', 'success');
                updateUI();
            } catch (error) {
                console.error('结束拍卖失败:', error);
                showNotification('结束拍卖失败: ' + error.message, 'error');
            } finally {
                endAuctionBtn.disabled = false;
                endAuctionBtn.textContent = '结束拍卖';
            }
        }

        // 更新UI
        async function updateUI() {
            try {
                // 获取合约数据
                const highestBid = await auctionContract.methods.highestBid().call();
                console.log(highestBid);
                
                const highestBidder = await auctionContract.methods.highestBidder().call();
                // const ended = await auctionContract.methods.ended().call();
                const bidEndTime = await auctionContract.methods.bidEndTime().call();
                
                // 更新UI元素
                currentHighestBidEl.textContent = `${web3.utils.fromWei(highestBid, 'ether')} ETH`;
                currentHighestBidderEl.textContent = highestBidder !== '0x0000000000000000000000000000000000000000' ? 
                    shortenAddress(highestBidder) : '暂无';
                
                const endTime = new Date(parseInt(bidEndTime) * 1000);
                auctionEndTimeEl.textContent = endTime.toLocaleString();
                
                // auctionStatusEl.textContent = ended ? '已结束' : '进行中';
                
                // 更新倒计时
                initCountdown(parseInt(bidEndTime));
                
                // 更新按钮状态
                // if (ended) {
                //     placeBidBtn.disabled = true;
                //     placeBidBtn.classList.add('btn-disabled');
                //     endAuctionBtn.style.display = 'block';
                // } else {
                //     placeBidBtn.disabled = false;
                //     placeBidBtn.classList.remove('btn-disabled');
                //     endAuctionBtn.style.display = 'none';
                // }
                
                // 如果是所有者且拍卖未结束，显示结束拍卖按钮
                // if (isWalletConnected) {
                //     const owner = await auctionContract.methods.owner().call();
                //     if (currentAccount.toLowerCase() === owner.toLowerCase() && !ended) {
                //         endAuctionBtn.style.display = 'block';
                //     }
                // }
                
                // 获取竞标历史
                await updateBidHistory();
            } catch (error) {
                console.error('更新UI失败:', error);
                showNotification('更新数据失败: ' + error.message, 'error');
            }
        }

        // 更新竞标历史
        async function updateBidHistory() {
            try {
                // 注意：合约本身不存储完整的竞标历史，这里只是示例
                // 实际应用中可能需要使用事件日志或后端服务来获取完整历史
                
                // 模拟一些历史数据
                const mockHistory = [
                    { bidder: '0x1234...5678', amount: '1.5', timestamp: Math.floor(Date.now() / 1000) - 3600 },
                    { bidder: '0x8765...4321', amount: '2.0', timestamp: Math.floor(Date.now() / 1000) - 1800 },
                    { bidder: '0x1111...2222', amount: '1.0', timestamp: Math.floor(Date.now() / 1000) - 7200 }
                ];
                
                let html = '';
                if (mockHistory.length === 0) {
                    html = `
                        <tr>
                            <td colspan="3" style="text-align: center;">暂无竞标记录</td>
                        </tr>
                    `;
                } else {
                    mockHistory.forEach(bid => {
                        const date = new Date(bid.timestamp * 1000);
                        html += `
                            <tr>
                                <td>${shortenAddress(bid.bidder)}</td>
                                <td>${bid.amount} ETH</td>
                                <td>${date.toLocaleString()}</td>
                            </tr>
                        `;
                    });
                }
                bidHistoryEl.innerHTML = html;
            } catch (error) {
                console.error('更新竞标历史失败:', error);
            }
        }

        // 初始化倒计时
        function initCountdown(endTime) {
            const now = Math.floor(Date.now() / 1000);
            const remaining = endTime - now;
            
            if (remaining <= 0) {
                countdownEl.textContent = '00:00:00';
                auctionStatusEl.textContent = '已结束';
                return;
            }
            
            const hours = Math.floor(remaining / 3600);
            const minutes = Math.floor((remaining % 3600) / 60);
            const seconds = remaining % 60;
            
            countdownEl.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }

        // 更新余额
        async function updateBalance() {
            if (!isWalletConnected) return;
            
            try {
                ethBalance = await web3.eth.getBalance(currentAccount);
                ethBalanceEl.textContent = `${web3.utils.fromWei(ethBalance, 'ether')} ETH`;
            } catch (error) {
                console.error('获取余额失败:', error);
                ethBalanceEl.textContent = '获取余额失败';
            }
        }

        // 显示通知
        function showNotification(message, type) {
            notificationEl.style.display = 'flex';
            notificationTextEl.textContent = message;
            notificationEl.className = `notification notification-${type}`;
            
            setTimeout(() => {
                notificationEl.style.display = 'none';
            }, 5000);
        }

        // 缩短地址显示
        function shortenAddress(address) {
            if (!address || address === '0x0000000000000000000000000000000000000000') return '';
            return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
        }
    </script>
</body>
</html>